import Cesium from '../Ces/Cesium'
import WeatherData from '../Weather/WeatherData'
import WeDataParserBase from '../Display/WeDataParserBase'

class ParserW3D extends WeDataParserBase {
  requestImage(url, getUrlCallback) {
    if (getUrlCallback) url = getUrlCallback(url) + ''
    return Cesium.Resource.fetchArrayBuffer(url).then(arrayBuffer => {
      return Promise.resolve(this.parse(arrayBuffer))
    })
  }

  parse(arrayBuffer) {
    const image = WeatherData.parseW3dm(arrayBuffer)
    const data: any = {
      west: -180,
      south: -90,
      east: 180,
      north: 90,
    }

    data.source = image.source
    data.source.flipY = false

    if (Cesium.defined(image.rectangle)) {
      data.west = image.rectangle.west
      data.south = image.rectangle.south
      data.east = image.rectangle.east
      data.north = image.rectangle.north
    }

    if (Cesium.defined(image.position) && Cesium.defined(image.size)) {
      const longitude = image.position.x
      const latitude = image.position.y
      const radius = Cesium.Ellipsoid.WGS84.radii.x

      const radiusInLat = Math.cos(Cesium.Math.toRadians(latitude)) * radius
      const meterPerDegreesInLat = radiusInLat * Cesium.Math.TWO_PI / 360.0

      const halfWidth = image.size.width / meterPerDegreesInLat * 0.5
      const halfHeight = image.size.height / meterPerDegreesInLat * 0.5

      data.west = longitude - halfWidth
      data.south = latitude - halfHeight
      data.east = longitude + halfWidth
      data.north = latitude + halfHeight

    }
    data.externalData = {
      size: image.size,
    }

    return data
  }
}


export default ParserW3D
